<template>
  <view class="page-container">
    <!-- 固定头部区域 -->
    <view class="fixed-header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <!-- 导航栏 -->
      <view class="nav-bar">
        <view class="title">发现</view>
      </view>

      <!-- 搜索框 -->
      <view class="search-box">
        <view class="search-input-box">
          <text class="icon-search">🔍</text>
          <input type="text" class="search-input" placeholder="搜索智能体" placeholder-class="search-placeholder"
            v-model="searchKey" @confirm="handleSearch" />
        </view>
      </view>

      <!-- 标签栏 -->
      <scroll-view scroll-x class="tag-scroll" :show-scrollbar="false">
        <view v-for="(tag, index) in tags" :key="index" :class="['tag-item', currentTag === index ? 'active' : '']"
          @tap="switchTag(index)">
          {{ tag }}
        </view>
      </scroll-view>
    </view>

    <!-- 可滚动内容区域 -->
    <scroll-view 
      class="scrollable-content"
      :style="{ top: `calc(${statusBarHeight}px + 88rpx + 88rpx + 88rpx)` }"
      scroll-y 
      @scrolltolower="loadMore" 
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="refresh"
    >
      <!-- AI列表 -->
      <view class="device-list">
        <view 
          :class="['device-item', item.is_premium || item.isPremium ? 'premium-item' : '']" 
          v-for="item in deviceList" 
          :key="item.id"
        >
          <!-- 高级模型专属徽章 - 移动到卡片左上角 -->
          <view v-if="item.is_premium || item.isPremium" class="premium-badge">
            <text class="premium-icon">👑</text>
            <text class="premium-text">高级</text>
          </view>
          
          <!-- 头像容器 -->
          <view class="avatar-container">
            <image 
              class="avatar" 
              :src="item.icon || defaultAvatar" 
              mode="aspectFill" 
            />
          </view>
          
          <view class="content">
            <view class="title-container">
              <view :class="['title', item.is_premium || item.isPremium ? 'premium-title' : '']">
                {{ item.name }}
              </view>
            </view>
            <view :class="['desc', item.is_premium || item.isPremium ? 'premium-desc' : '']">
              {{ item.description }}
            </view>
            <view class="chat-info">
              <view :class="['chat-count', item.is_premium || item.isPremium ? 'premium-info' : '']">
                {{ formatNumber(item.collectionCount || 0) }}次收藏 · {{ item.creatorName || getUserName(item) }}
              </view>
            </view>
          </view>
          
          <view class="action-btns">
            <view class="collect-btn" @tap.stop="handleCollect(item)">
              <text :class="['iconfont', item.isCollected ? 'icon-star-filled' : 'icon-star']"></text>
            </view>
            <view 
              :class="[
                'add-btn', 
                item.configured ? 'configured' : '',
                item.is_premium || item.isPremium ? 'premium-btn' : ''
              ]" 
              @tap.stop="handleAdd(item)"
            >
              {{ item.configured ? '✓' : '+' }}
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 固定底部导航 -->
    <view class="fixed-footer">
      <TabBar :current-tab="1" />
    </view>
  </view>
</template>

<script setup>
// discover.vue的<script setup>部分
import { ref, onMounted, onUnmounted } from 'vue'
import { message } from '@/utils'
import system from '@/utils/system'
import TabBar from '@/components/TabBar/TabBar.vue'
const hardwareStore = useHardwareStore()
const deviceStore = useDeviceStore()
const statusBarHeight = system.getStatusBarHeight()
import { useDeviceStore, useHardwareStore } from '@/stores'
import api from '@/api/modules';
// 默认头像
const defaultAvatar = '/static/images/default-avatar.png'

// 设置路由变化监听
const setupRouteWatcher = () => {
  // 获取当前页面路由对象
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  if (currentPage) {
    // 手动监听页面显示事件
    const onShowHandler = () => {
      console.log('discover页面显示，刷新数据');
      // 判断是否需要重新加载数据，防止频繁刷新
      const now = Date.now();
      const lastLoadTime = uni.getStorageSync('discoverLastLoadTime') || 0;
      
      // 超过30秒或列表为空时才刷新
      if (now - lastLoadTime > 30000 || deviceList.value.length === 0) {
        currentPage.value = 1;
        loadData().then(() => {
          uni.setStorageSync('discoverLastLoadTime', Date.now());
        });
      }
    };
    
    // 添加页面显示事件监听
    currentPage.onShow = function() {
      onShowHandler();
      // 保留原有的onShow逻辑，如果有的话
      if (this.$mp && this.$mp.page && this.$mp.page._onShow) {
        this.$mp.page._onShow();
      }
    };
  }
};

// 搜索相关
const searchKey = ref('')
const originalList = ref([]) // 保存原始数据
// 搜索处理
const handleSearch = () => {
  const keyword = searchKey.value.trim().toLowerCase()
  if (!keyword) {
    deviceList.value = originalList.value // 搜索词为空时显示所有数据
    return
  }

  // 前端实现模糊搜索
  deviceList.value = originalList.value.filter(item =>
    item.name.toLowerCase().includes(keyword) ||
    item.description.toLowerCase().includes(keyword)
  )
}

// 标签配置 
const tags = ['推荐', '助手', '教育', '娱乐', '工具']
const currentTag = ref(0)

// 底部导航配置
const tabs = [{
    text: '对话',
    icon: 'icon-message'
  },
  {
    text: '发现',
    icon: 'icon-search'
  },
  {
    text: '我的',
    icon: 'icon-user'
  }
]
const currentTab = ref(1) // 当前在发现页

const switchTag = (index) => {
  currentTag.value = index
  currentPage.value = 1
  loadData()
}

// 列表数据
const deviceList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const currentPage = ref(1)
const pageSize = 10

// 加载数据
const loadData = async () => {
  if (loading.value) return;
  loading.value = true;

  try {
    const res = await deviceStore.loadPublicDevices({
      current: currentPage.value,
      size: pageSize,
      category: currentTag.value === 0 ? '' : tags[currentTag.value]
    });

    if (res.code === 200) {
      const records = res.data.records || [];
      // 调试日志，查看原始数据
      console.log('API返回原始数据:', records.slice(0, 2));
      
      // 映射数据，确保属性名称一致，包括会员字段
      const mappedRecords = records.map(record => {
        return {
          ...record,
          // 确保保留原始name字段
          id: record.id,
          name: record.name || `智能体${record.id}`, // 保留name字段，如果不存在则使用默认值
          icon: record.avatar || record.icon,
          usageCount: record.collectionCount || 0,
          collectionCount: record.collectionCount || 0,
          creatorName: getUserName(record), // 使用新的获取用户名方法
          isCollected: record.collected || record.isCollected || false,
          description: record.description || '',
          // 添加会员字段支持
          is_premium: record.is_premium || false,
          isPremium: record.isPremium || record.is_premium || false
        };
      });
      
      // 调试日志，查看映射后的数据
      console.log('映射后数据:', mappedRecords.slice(0, 2));
      
      if (currentPage.value === 1) {
        // 第一页直接替换
        deviceList.value = mappedRecords;
        originalList.value = mappedRecords;
      } else {
        // 后续页面，先检查是否有重复，只添加新的记录
        const newRecords = mappedRecords.filter(record => 
          !deviceList.value.some(existingRecord => 
            existingRecord.id === record.id
          )
        );
        deviceList.value.push(...newRecords);
        originalList.value.push(...newRecords);
      }
    } else {
      throw new Error(res.message || '加载失败');
    }
  } catch (error) {
    console.error('加载失败:', error);
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    // 如果是下拉刷新触发的，延迟重置状态
    if (refreshing.value) {
      setTimeout(() => {
        refreshing.value = false; // ← 延迟1.5秒后结束刷新动画
      }, 1000);
    }
  }
}

// 获取用户名称的辅助函数 - 修复版
const getUserName = (device) => {
  // 系统用户特殊处理
  if (device.userId === 0 || device.userId === null || device.userId === undefined) {
    return '系统';
  }
  
  // 优先使用creatorName
  if (device.creatorName && device.creatorName.trim() !== '') {
    return device.creatorName;
  }
  
  // 尝试其他可能的字段
  if (device.creator_name && device.creator_name.trim() !== '') {
    return device.creator_name;
  }
  
  // 昵称候选字段
  const nicknames = [device.nickname, device.userName, device.username];
  for (const name of nicknames) {
    if (name && name.trim() !== '') {
      return name;
    }
  }
  
  // 兜底返回
  return `用户${device.userId}`;
}

// 加载更多
const loadMore = () => {
  currentPage.value++
  loadData()
}

// 刷新
const refresh = async () => {
  if (refreshing.value) return
  refreshing.value = true
  currentPage.value = 1
  await loadData()
  // 2秒后重置刷新状态
  setTimeout(() => {
    refreshing.value = false
    uni.stopPullDownRefresh()
  }, 1000)
}

// 更新智能体的处理函数
const handleAdd = async (device) => {
  try {
    // 首先检查设备是否已配置该智能体
    if (device.configured) {
      uni.showToast({
        title: '设备已配置该智能体',
        icon: 'success'
      });
      return;
    }
    
    // First collect the device if not already collected
    if (!device.isCollected) {
      const collectRes = await deviceStore.collectDevice(device.id);
      if (collectRes && collectRes.code === 200) {
        device.isCollected = true;
        device.collected = true;
        
        uni.showToast({
          title: '收藏成功',
          icon: 'success'
        });
      } else {
        throw new Error('收藏设备失败');
      }
    }
    
    // Try to use the last registered device from BlueWifi page
    let hardwareDevice = hardwareStore.lastRegisteredDevice;
    let deviceMac = hardwareDevice?.macAddress;
    
    // If we don't have a device, try to get one
    if (!deviceMac) {
      try {
        // Get the user ID
        const userId = uni.getStorageSync('userId') || 1;
        
        const userDevicesRes = await api.hardware.getUserDevices(userId);
        if (userDevicesRes.code === 200 && userDevicesRes.data && userDevicesRes.data.length > 0) {
          // Use the most recently registered device
          hardwareDevice = userDevicesRes.data[0];
          hardwareStore.lastRegisteredDevice = hardwareDevice;
          deviceMac = hardwareDevice.macAddress;
        } else {
          // No devices found, prompt to add one
          uni.showModal({
            title: '提示',
            content: '未找到硬件设备，请先添加设备',
            confirmText: '去配置',
            success: (res) => {
              if (res.confirm) {
                uni.navigateTo({
                  url: '/pages/BlueWifi/BlueWifi'
                });
              }
            }
          });
          return;
        }
      } catch (error) {
        console.error('获取用户设备失败:', error);
        uni.showModal({
          title: '提示',
          content: '未找到硬件设备，请先添加设备',
          confirmText: '去配置',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/BlueWifi/BlueWifi'
              });
            }
          }
        });
        return;
      }
    }
    
    // Now we should have a device
    if (!deviceMac) {
      uni.showModal({
        title: '提示',
        content: '未找到硬件设备，请先添加设备',
        confirmText: '去配置',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/BlueWifi/BlueWifi'
            });
          }
        }
      });
      return;
    }
    
    // Use the new API to configure the device
    const success = await hardwareStore.configureDeviceAgent(deviceMac, device.id);
    
    if (success) {
      // Mark this device as configured in the local list
      device.configured = true;
      
      // Also mark other devices as not configured (only one can be active)
      deviceList.value.forEach(item => {
        if (item.id !== device.id) {
          item.configured = false;
        }
      });
      
      uni.showToast({
        title: '设备AI配置成功',
        icon: 'success'
      });
    }
  } catch (error) {
    console.error('操作失败:', error);
    uni.showToast({
      title: error.message || '操作失败',
      icon: 'none'
    });
  }
};

// 收藏智能体
const handleCollect = async (device) => {
  try {
    // 乐观更新界面
    const currentlyCollected = device.isCollected || device.collected;
    // 切换收藏状态
    device.isCollected = !currentlyCollected;
    device.collected = !currentlyCollected;
    
    uni.showToast({
      title: currentlyCollected ? '取消收藏成功' : '收藏成功',
      icon: 'success'
    })
    
    // 异步处理服务器请求
    const res = await deviceStore.toggleCollect(device.id);
    
    // 如果服务器出错，恢复原状态
    if (!res || res.code !== 200) {
      device.isCollected = currentlyCollected;
      device.collected = currentlyCollected;
      
      uni.showToast({
        title: '操作失败，请稍后再试',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('操作失败:', error)
    uni.showToast({
      title: '网络错误，请稍后再试',
      icon: 'none'
    })
  }
}

// Banner点击
const handleBannerTap = () => {
  // 跳转到蓝牙配网页面
  uni.navigateTo({
    url: '/pages/BlueWifi/BlueWifi'
  })
}

// 格式化数字
const formatNumber = (num) => {
  const value = Number(num || 0)
  if (value === 0) return "0"
  return value.toString()
}

// 切换标签页
const switchTab = (index) => {
  const routes = [
    '/pages/index/index',
    '/pages/discover/discover',
    '/pages/my/my'
  ]
  uni.switchTab({
    url: routes[index]
  })
}

// 监听登录状态变化事件
const setupLoginListener = () => {
  uni.$on('loginStateChanged', (data) => {
    console.log('发现页面检测到登录状态变化，强制刷新数据');
    // 清除缓存数据
    uni.removeStorageSync('discoverLastLoadTime');
    // 重置页码
    currentPage.value = 1;
    // 强制刷新
    refreshing.value = true;
    // 加载数据
    loadData().finally(() => {
      setTimeout(() => {
        refreshing.value = false;
      }, 500);
    });
  })
}

onMounted(() => {
  // 设置路由变化监听
  setupRouteWatcher();
  
  loadData();
  setupLoginListener();
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  uni.$off('loginStateChanged');
})
</script>

<style lang="scss">
.page-container {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  background: #f8f9fa;
  
  // 固定头部
  .fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
    background: #fff;

    // 导航栏
    .nav-bar {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 30rpx;
      background: #fff;
      border-bottom: 1px solid #f5f5f5;

      .title {
        font-size: 36rpx;
        font-weight: 600;
        color: #333;
      }
    }

    // 搜索框
    .search-box {
      padding: 24rpx 30rpx;
      background: #fff;

      .search-input-box {
        display: flex;
        align-items: center;
        background: #f5f6f7;
        border-radius: 36rpx;
        padding: 16rpx 24rpx;

        .icon-search {
          margin-right: 12rpx;
          font-size: 28rpx;
          color: #999;
        }

        .search-input {
          flex: 1;
          height: 40rpx;
          min-height: 40rpx;
          font-size: 28rpx;
          color: #333;
        }

        .search-placeholder {
          color: #999;
        }
      }
    }

    // 标签栏
    .tag-scroll {
      padding: 0 30rpx;
      white-space: nowrap;
      background: #fff;
      height: 88rpx;
      border-bottom: 1px solid #f5f5f5;

      .tag-item {
        display: inline-block;
        padding: 24rpx 32rpx;
        margin-right: 24rpx;
        font-size: 28rpx;
        color: #666;
        position: relative;

        &.active {
          color: #5677fc;
          font-weight: 500;
        }

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }

  // 可滚动内容区域
  .scrollable-content {
    position: fixed;
    left: 0;
    right: 0;
    bottom: calc(110rpx + env(safe-area-inset-bottom));
    background: #f8f9fa;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding-bottom: 20rpx;
    padding-top: 30rpx; // 添加顶部内边距

    // AI列表
    .device-list {
      padding: 10px 30rpx;

      .device-item {
        display: flex;
        align-items: center;
        background: #fff;
        border-radius: 16rpx;
        padding: 24rpx;
        margin-bottom: 24rpx;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
        position: relative;
        overflow: hidden;

        // 高级模型样式 - 简化版
        &.premium-item {
          // 保持基本的白色背景，移除特殊效果
        }

        // 高级徽章 - 移动到卡片左上角
        .premium-badge {
          position: absolute;
          top: 8rpx;
          left: 8rpx;
          background: linear-gradient(135deg, #ffd700, #ffed4e);
          color: #8b4513;
          padding: 4rpx 10rpx;
          border-radius: 8rpx;
          font-size: 20rpx;
          font-weight: 600;
          display: flex;
          align-items: center;
          z-index: 10;
          box-shadow: 0 2rpx 8rpx rgba(255, 215, 0, 0.3);
          line-height: 1;

          .premium-icon {
            margin-right: 4rpx;
            font-size: 22rpx;
          }

          .premium-text {
            font-size: 20rpx;
          }
        }

        // 头像容器
        .avatar-container {
          position: relative;
          margin-right: 20rpx;
          flex-shrink: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .avatar {
            width: 100rpx;
            height: 100rpx;
            border-radius: 20rpx;
            flex-shrink: 0;
          }
        }

        .content {
          flex: 1;
          overflow: hidden;
          
          .title-container {
            display: flex;
            align-items: center;
            margin-bottom: 8rpx;
            
            .title {
              font-size: 32rpx;
              font-weight: 600;
              color: #333;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              flex: 1;
              line-height: 1.3;
              
              &.premium-title {
                color: #d4af37;
                font-weight: 700;
              }
            }
          }

          .desc {
            font-size: 26rpx;
            color: #666;
            margin-bottom: 12rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.4;
            
            &.premium-desc {
              color: #8b6914;
            }
          }

          .chat-info {
            display: flex;
            align-items: center;
            
            .chat-count {
              font-size: 24rpx;
              color: #999;
              line-height: 1.2;
              
              &.premium-info {
                color: #b8860b;
                font-weight: 500;
              }
            }
          }
        }

        .action-btns {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin-left: 20rpx;
          flex-shrink: 0;
          
          .collect-btn {
            margin-bottom: 16rpx;
            width: 60rpx;
            height: 60rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            
            .iconfont {
              font-size: 40rpx;
              color: #999;
              
              &.icon-star-filled {
                color: #ffcc00;
              }
            }
          }
          
          .add-btn {
            width: 60rpx;
            height: 60rpx;
            background: #5677fc;
            color: #fff;
            border-radius: 30rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 36rpx;
            font-weight: bold;
            transition: all 0.2s ease;
            
            &.configured {
              background: #52c41a;
            }
            
            &.premium-btn {
              background: linear-gradient(135deg, #ffd700, #ffed4e);
              color: #8b4513;
              
              &.configured {
                background: linear-gradient(135deg, #32cd32, #90ee90);
                color: #006400;
              }
            }
          }
        }
        
        &:active {
          opacity: 0.9;
          transform: scale(0.98);
        }
      }
    }
  }

  // 固定底部导航
  .fixed-footer {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100;
    background: #fff;
    padding-bottom: env(safe-area-inset-bottom);
    border-top: 1px solid #f5f5f5;

    .tab-bar {
      height: 110rpx;
      display: flex;
      align-items: center;
      justify-content: space-around;

      .tab-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 10rpx 0;

        .iconfont {
          font-size: 44rpx;
          color: #999;
          margin-bottom: 4rpx;

          &.icon-message:before { content: '\e900'; }
          &.icon-search:before { content: '\e901'; }
          &.icon-add:before { content: '\e902'; }
          &.icon-notification:before { content: '\e903'; }
          &.icon-user:before { content: '\e904'; }
        }

        .text {
          font-size: 24rpx;
          color: #999;
          line-height: 1;
        }

        &.active {
          .iconfont,
          .text {
            color: #5677fc;
          }
        }
      }
    }
  }
}

// 动画效果 - 仅保留必要的动画
@keyframes sparkle {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.6;
    transform: scale(1.2);
  }
}
</style>